﻿using System;
using System.Collections.Generic;
using System.Text;
using PreeRegisterModel;
using System.Data;
using PreeRegisterDAL;
using DrSoftsFrame;
using Newtonsoft.Json.Linq;
using System.Web;

namespace PreeRegisterBLL
{
    public class SearchBLL
    {
        #region 长治和平接口 查询缴费项 订单支付

        /// <summary>
        /// 长治和平 查询缴费项
        /// </summary>
        /// <param name="notPayRequestModel"></param>
        /// <returns></returns>
        public static NotPayResponseModel NotPay_CZHP(NotPayRequestModel notPayRequestModel)
        {
            try
            {
                //查询缴费项
                NotPayResponseModel notPayResponseModel = new PreeRegisterModel.NotPayResponseModel();

                //获取查询缴费项
                List<NotPayResponseItemModel> NotPayResponseItemModel_list = new List<NotPayResponseItemModel>();

                try
                {
                    string url_searchNopay = CommonBLL.GetConfig("CZHP_ADDR") + "GetAppointmentByOrderId?parameters=";
                    StringBuilder head = new StringBuilder();
                    StringBuilder body = new StringBuilder();

                    head.Append("{head:\"\"");
                    body.Append(" {");
                    body.AppendFormat("\"OrderId\": \"{0}\"", CommonBLL.GetOrderId(notPayRequestModel.orderid, 3));
                    body.Append("}");
                    CommonBLL.WriteFile_New(CommonBLL.bizCode_searchNopay, "1：查询缴费项接口请求body明文：\r\n" + CommonBLL.ConvertJsonString(body.ToString()));
                    string postData_searchNopay = string.Format("{0},body:\"{1}", head.ToString(), HttpUtility.UrlEncode(Security.Base64.EncodeBase64(body.ToString())));
                    postData_searchNopay += "\"}";
                    url_searchNopay += postData_searchNopay;
                    CommonBLL.WriteFile_New(CommonBLL.bizCode_searchNopay, "2：查询缴费项接口请求密文：\r\n" + url_searchNopay);
                    JObject obj_searchNopay = CommonBLL.HttpPost_CZHP(url_searchNopay);
                    CommonBLL.WriteFile_New(CommonBLL.bizCode_searchNopay, "3：查询缴费项接口返回明文：\r\n" + CommonBLL.ConvertJsonString(obj_searchNopay.ToString()));
                    string code_searchNopay = obj_searchNopay["code"].ToString();

                    if (string.Equals(code_searchNopay, "1"))
                    {
                        string code = "";
                        string msg = "";
                        var mJObj = JArray.Parse(obj_searchNopay["result"].ToString());
                        foreach (var drNotPay in mJObj)
                        {
                            NotPayResponseItemModel notPayResponseItemModel = new NotPayResponseItemModel();
                            //0 Available 2 Charged 3 Triaged  4 Appiontmented
                            if (string.Equals(drNotPay["AppointmentOrder"]["Status"].ToString(), "Available")//0
                                || string.Equals(drNotPay["AppointmentOrder"]["Status"].ToString(), "Charged")//2
                                || string.Equals(drNotPay["AppointmentOrder"]["Status"].ToString(), "Triaged")//3
                                 || string.Equals(drNotPay["AppointmentOrder"]["Status"].ToString(), "Appiontmented"))//4
                            {
                                code = "1";
                                msg = "查询缴费项成功";
                                notPayResponseItemModel.name = drNotPay["Patient"]["PatientName"].ToString();
                                notPayResponseItemModel.gender = drNotPay["Patient"]["Gender"].ToString();
                                notPayResponseItemModel.state = "1";
                                notPayResponseItemModel.dname = drNotPay["WorkSchedule"]["Department"]["Name"].ToString();
                                notPayResponseItemModel.docname = drNotPay["WorkSchedule"]["Doctor"]["Name"].ToString();
                                notPayResponseItemModel.time = drNotPay["AppointmentOrder"]["OrderDate"].ToString();
                                notPayResponseItemModel.cateid = drNotPay["AppointmentType"].ToString() == "预约" ? "1" : "";
                                notPayResponseItemModel.title = notPayResponseItemModel.cateid == "1" ? "挂号费" : "诊间支付";
                                notPayResponseItemModel.price = drNotPay["AppointmentOrder"]["Amount"].ToString();

                                notPayResponseItemModel.orderid = notPayRequestModel.orderid;//drNotPay["AppointmentOrder"]["OrderId"].ToString();
                                notPayResponseItemModel.hospitalcode = "1";
                                NotPayResponseItemModel_list.Add(notPayResponseItemModel);
                            }
                            else
                            {
                                code = "0";
                                msg = "没有要缴费的信息。";
                            }
                        }
                        notPayResponseModel.items = NotPayResponseItemModel_list;
                        notPayResponseModel.code = code;
                        notPayResponseModel.msg = msg;

                    }
                }
                catch (Exception err)
                {
                    throw err;
                }
                //返回
                CommonBLL.WriteFile_New(CommonBLL.bizCode_searchNopay, notPayResponseModel.msg);
                return notPayResponseModel;
            }
            catch (Exception err)
            {
                throw;
            }
        }

        public static PayOrderResponseModel PayOrder(PayOrderRequestModel payOrderRequestModel)
        {
            PayOrderResponseModel PayOrderResponseModel = new PayOrderResponseModel();
            //查询 hars_appointmentrecord
            if (string.Equals("1", payOrderRequestModel.opcode))
            {
                hars_appointmentrecord bll = new hars_appointmentrecord();
                DataSet ds = bll.GetList(string.Format(" isdelete=0 and orderid='{0}'", payOrderRequestModel.orderid));
                if (ds != null && ds.Tables[0].Rows.Count > 0)
                {
                    PayOrderResponseModel.card = ds.Tables[0].Rows[0]["card"].ToString();
                    PayOrderResponseModel.cout = ds.Tables[0].Rows[0]["cout"].ToString();
                    PayOrderResponseModel.dcount = ds.Tables[0].Rows[0]["dcount"].ToString();
                    PayOrderResponseModel.iid = ds.Tables[0].Rows[0]["iid"].ToString();
                    PayOrderResponseModel.name = ds.Tables[0].Rows[0]["name"].ToString();
                    PayOrderResponseModel.oid = ds.Tables[0].Rows[0]["oid"].ToString();
                    PayOrderResponseModel.response = "";
                    PayOrderResponseModel.state = ds.Tables[0].Rows[0]["state"].ToString();
                    PayOrderResponseModel.tel = ds.Tables[0].Rows[0]["tel"].ToString();
                    PayOrderResponseModel.wid = ds.Tables[0].Rows[0]["wid"].ToString();
                    PayOrderResponseModel.price = ds.Tables[0].Rows[0]["price"].ToString();
                    PayOrderResponseModel.price2 = ds.Tables[0].Rows[0]["price2"].ToString();
                    PayOrderResponseModel.ofee = ds.Tables[0].Rows[0]["ofee"].ToString();
                }
            }
            //查询  hars_notifyhistask
            else if (string.Equals("2", payOrderRequestModel.opcode))
            {
                hars_notifyhistask bll = new hars_notifyhistask();
                DataSet ds = bll.GetList(string.Format(" 1=1 and orderno='{0}'", payOrderRequestModel.orderid));
                PayOrderResponseModel.card = "";
                PayOrderResponseModel.cout = "";
                PayOrderResponseModel.dcount = "";
                PayOrderResponseModel.iid = "";
                PayOrderResponseModel.name = "";
                PayOrderResponseModel.oid = "";
                PayOrderResponseModel.response = ds.Tables[0].Rows[0]["response"].ToString();
                PayOrderResponseModel.state = ds.Tables[0].Rows[0]["state"].ToString();
                PayOrderResponseModel.tel = "";
                PayOrderResponseModel.wid = "";
                PayOrderResponseModel.price = "";
                PayOrderResponseModel.price2 = "";
                PayOrderResponseModel.ofee = "";
            }
            return PayOrderResponseModel;
        }

        /// <summary>
        /// 长治和平 查询缴费项【新】
        /// </summary>
        /// <param name="notPayRequestModel"></param>
        /// <returns></returns>
        public static NotPayResponseModel NotPay_CZHP_New(NotPayRequestModel notPayRequestModel)
        {
            try
            {
                //查询缴费项
                NotPayResponseModel notPayResponseModel = new PreeRegisterModel.NotPayResponseModel();

                //获取查询缴费项
                List<NotPayResponseItemModel> NotPayResponseItemModel_list = new List<NotPayResponseItemModel>();

                try
                {
                    string code = "";
                    string msg = "";
                    hars_appointmentrecord bll = new hars_appointmentrecord();
                    NotPayResponseItemModel notPayResponseItemModel = new NotPayResponseItemModel();
                    if (!string.IsNullOrEmpty(notPayRequestModel.orderid))
                    {
                        DataSet ds = bll.GetList(string.Format(" isdelete=0 and orderid='{0}'", notPayRequestModel.orderid));
                        if (ds != null && ds.Tables[0].Rows.Count > 0)
                        {
                            code = "1";
                            msg = "查询缴费项成功";
                            notPayResponseItemModel.name = ds.Tables[0].Rows[0]["name"].ToString();
                            notPayResponseItemModel.gender = ds.Tables[0].Rows[0]["gender"].ToString();
                            notPayResponseItemModel.state = "1";
                            notPayResponseItemModel.dname = ds.Tables[0].Rows[0]["deptname"].ToString();
                            notPayResponseItemModel.docname = ds.Tables[0].Rows[0]["doctorname"].ToString();
                            notPayResponseItemModel.time = ds.Tables[0].Rows[0]["tdate"].ToString();
                            notPayResponseItemModel.cateid = "1";
                            notPayResponseItemModel.title = notPayResponseItemModel.cateid == "1" ? "挂号费" : "诊间支付";
                            double ofee = double.Parse(ds.Tables[0].Rows[0]["ofee"].ToString()) / 100;
                            double price = double.Parse(ds.Tables[0].Rows[0]["price"].ToString()) / 100;
                            double price2 = double.Parse(ds.Tables[0].Rows[0]["price2"].ToString()) / 100;

                            double amount = ofee + price + price2;
                            notPayResponseItemModel.price = amount.ToString();//

                            notPayResponseItemModel.orderid = notPayRequestModel.orderid;
                            notPayResponseItemModel.hospitalcode = "1";
                            NotPayResponseItemModel_list.Add(notPayResponseItemModel);

                            notPayResponseModel.items = NotPayResponseItemModel_list;
                            notPayResponseModel.code = code;
                            notPayResponseModel.msg = msg;
                        }
                        else
                        {
                            code = "0";
                            msg = "查询缴费项接口，未查询到预约信息，错误代码：001";
                        }
                    }
                    else
                    {
                        code = "0";
                        msg = "查询缴费项接口，orderid 不能为空，错误代码：002";
                    }

                }
                catch (Exception err)
                {
                    throw err;
                }
                //返回
                CommonBLL.WriteFile_New(CommonBLL.bizCode_searchNopay, notPayResponseModel.msg);
                return notPayResponseModel;
            }
            catch (Exception err)
            {
                throw;
            }
        }

        /// <summary>
        /// 长治和平 支付接口
        /// </summary>
        /// <param name="payResultRequestModel"></param>
        /// <returns></returns>
        public static PayResultResponseItemModel PayResult_CZHP(PayResultRequstModel payResultRequestModel)
        {
            try
            {
                PayResultResponseItemModel payResultResponseItemModel = new PayResultResponseItemModel();
                try
                {
                    string url_payResult = CommonBLL.GetConfig("CZHP_ADDR") + "GetAppointmentByOrderId?parameters=";
                    StringBuilder head = new StringBuilder();
                    StringBuilder body = new StringBuilder();

                    head.Append("{head:\"\"");
                    body.Append(" {");
                    body.AppendFormat("\"OrderId\": \"{0}\"", CommonBLL.GetOrderId(payResultRequestModel.orderid, 3));
                    body.Append("}");
                    CommonBLL.WriteFile_New(CommonBLL.bizCode_payResult, "1：订单支付接口请求body明文：\r\n" + CommonBLL.ConvertJsonString(body.ToString()));
                    string postData_payResult = string.Format("{0},body:\"{1}", head.ToString(), HttpUtility.UrlEncode(Security.Base64.EncodeBase64(body.ToString())));
                    postData_payResult += "\"}";
                    url_payResult += postData_payResult;
                    JObject obj_payResult = CommonBLL.HttpPost_CZHP(url_payResult);
                    CommonBLL.WriteFile_New(CommonBLL.bizCode_payResult, "2：订单支付接口请求密文：\r\n" + url_payResult);
                    string code_payResult = obj_payResult["code"].ToString();
                    CommonBLL.WriteFile_New(CommonBLL.bizCode_payResult, "3：订单支付接口返回明文：\r\n" + CommonBLL.ConvertJsonString(obj_payResult.ToString()));

                    if (string.Equals(code_payResult, "1"))
                    {
                        var mJObj = JArray.Parse(obj_payResult["result"].ToString());
                        foreach (var drNotPay in mJObj)
                        {
                            //0 Available 2 Charged 3 Triaged  4 Appiontmented
                            if (string.Equals(drNotPay["AppointmentOrder"]["Status"].ToString(), "Available")//0
                                || string.Equals(drNotPay["AppointmentOrder"]["Status"].ToString(), "Charged")//2
                                || string.Equals(drNotPay["AppointmentOrder"]["Status"].ToString(), "Triaged"))//3
                            {
                                payResultResponseItemModel.code = "1";
                                payResultResponseItemModel.msg = "支付成功";
                                payResultResponseItemModel.cdiagnosetypename = drNotPay["WorkSchedule"]["Doctor"]["Rank"].ToString();
                                payResultResponseItemModel.cflowcode = CommonBLL.GetOrderId(drNotPay["AppointmentOrder"]["OrderId"].ToString(), 4);
                                payResultResponseItemModel.chousename = drNotPay["WorkSchedule"]["VisitRoom"].ToString();
                                payResultResponseItemModel.chousesectionname = drNotPay["WorkSchedule"]["VisitRoom"].ToString();
                                payResultResponseItemModel.cidentitycard = drNotPay["Patient"]["IdentityCard"].ToString();
                                payResultResponseItemModel.clocation = drNotPay["WorkSchedule"]["VisitRoom"].ToString();
                                payResultResponseItemModel.cpatientcode = drNotPay["Patient"]["IdentityCard"].ToString();
                                payResultResponseItemModel.cpatientname = drNotPay["Patient"]["PatientName"].ToString();
                                payResultResponseItemModel.csex = drNotPay["Patient"]["Gender"].ToString();
                                payResultResponseItemModel.ddiagnosetime = drNotPay["WorkSchedule"]["Date"].ToString();

                                payResultResponseItemModel.deptname = drNotPay["WorkSchedule"]["Department"]["Name"].ToString();
                                payResultResponseItemModel.diagnoseid = drNotPay["AppointmentOrder"]["OrderId"].ToString();
                                payResultResponseItemModel.doctorname = drNotPay["WorkSchedule"]["Doctor"]["Name"].ToString();
                                payResultResponseItemModel.ndiagnosenum = drNotPay["WorkDetail"]["AppointmentOrder"].ToString();
                                payResultResponseItemModel.nmoney = drNotPay["AppointmentOrder"]["Amount"].ToString();
                                //   payResultResponseItemModel_list.Add(payResultResponseItemModel);
                            }
                            else
                            {
                                payResultResponseItemModel.code = "1";
                                payResultResponseItemModel.msg = obj_payResult["msg"].ToString();
                                payResultResponseItemModel.cdiagnosetypename = "";
                                payResultResponseItemModel.cflowcode = "";
                                payResultResponseItemModel.chousename = "";
                                payResultResponseItemModel.chousesectionname = "";
                                payResultResponseItemModel.cidentitycard = "";
                                payResultResponseItemModel.clocation = "";
                                payResultResponseItemModel.cpatientcode = "";
                                payResultResponseItemModel.cpatientname = "";
                                payResultResponseItemModel.csex = "";
                                payResultResponseItemModel.ddiagnosetime = "";

                                payResultResponseItemModel.deptname = "";
                                payResultResponseItemModel.diagnoseid = "";
                                payResultResponseItemModel.doctorname = "";
                                payResultResponseItemModel.ndiagnosenum = "";
                                payResultResponseItemModel.nmoney = "";
                                //  payResultResponseItemModel_list.Add(payResultResponseItemModel);
                            }
                        }
                        //payResultResponseModel.items = payResultResponseItemModel_list;
                        //payResultResponseModel.code = code;
                        //payResultResponseModel.msg = msg;

                    }
                }
                catch (Exception err)
                {
                    throw err;
                }

                //返回
                CommonBLL.WriteFile_New(CommonBLL.bizCode_payResult, payResultResponseItemModel.msg);
                return payResultResponseItemModel;
            }
            catch (Exception err)
            {

                throw;
            }
        }

        /// <summary>
        /// 长治和平 支付接口【新】
        /// </summary>
        /// <param name="payResultRequestModel"></param>
        /// <returns></returns>
        public static PayResultResponseItemModel PayResult_CZHP_New2(PayResultRequstModel payResultRequestModel)
        {
            try
            {
                PayResultResponseItemModel payResultResponseItemModel = new PayResultResponseItemModel();
                try
                {
                    hars_appointmentrecord bll = new hars_appointmentrecord();
                    NotPayResponseItemModel notPayResponseItemModel = new NotPayResponseItemModel();
                    if (!string.IsNullOrEmpty(payResultRequestModel.orderid))
                    {
                        DataSet ds = bll.GetList(string.Format(" isdelete=0 and orderid='{0}'", payResultRequestModel.orderid));

                        if (ds != null && ds.Tables[0].Rows.Count > 0)
                        {
                            SearchBLL bll_search = new SearchBLL();
                            int yuyue_state = 0;
                            int order_state = 0;
                            string yuyue_msg = string.Empty;
                            string order_msg = string.Empty;

                            string orderJson = bll_search.GetOrderJson(payResultRequestModel.orderid, ds,
                              out yuyue_state, out yuyue_msg, out order_state, out order_msg);
                            if (string.Equals("-1000", yuyue_state))
                            {
                                //payResultResponseItemModel.code = yuyue_state.ToString() + "003";
                                payResultResponseItemModel.code = "-1000";//标识作废，系统自动退款。
                                payResultResponseItemModel.msg = "【预约挂号异常】：" + yuyue_msg;
                                payResultResponseItemModel.oid = "";
                                payResultResponseItemModel.cdiagnosetypename = "";
                                payResultResponseItemModel.cflowcode = "";
                                payResultResponseItemModel.chousename = "";
                                payResultResponseItemModel.chousesectionname = "";
                                payResultResponseItemModel.cidentitycard = "";
                                payResultResponseItemModel.clocation = "";
                                payResultResponseItemModel.cpatientcode = "";
                                payResultResponseItemModel.cpatientname = "";
                                payResultResponseItemModel.csex = "";
                                payResultResponseItemModel.ddiagnosetime = "";

                                payResultResponseItemModel.deptname = "";
                                payResultResponseItemModel.diagnoseid = "";
                                payResultResponseItemModel.doctorname = "";
                                payResultResponseItemModel.ndiagnosenum = "";
                                payResultResponseItemModel.nmoney = "";
                                payResultResponseItemModel.orderno = payResultRequestModel.orderid;
                                payResultResponseItemModel.hospsate = "";
                                payResultResponseItemModel.workid = "";
                                payResultResponseItemModel.resourceid = "";
                                payResultResponseItemModel.inum = "";
                                return payResultResponseItemModel;
                            }
                            if (yuyue_state != 1)
                            {
                                //payResultResponseItemModel.code = yuyue_state.ToString() + "003";
                                payResultResponseItemModel.code = "-5";//标识作废，系统自动退款。
                                payResultResponseItemModel.msg = "【预约挂号异常，系统自动退款】：" + yuyue_msg;
                                payResultResponseItemModel.oid = "";
                                payResultResponseItemModel.cdiagnosetypename = "";
                                payResultResponseItemModel.cflowcode = "";
                                payResultResponseItemModel.chousename = "";
                                payResultResponseItemModel.chousesectionname = "";
                                payResultResponseItemModel.cidentitycard = "";
                                payResultResponseItemModel.clocation = "";
                                payResultResponseItemModel.cpatientcode = "";
                                payResultResponseItemModel.cpatientname = "";
                                payResultResponseItemModel.csex = "";
                                payResultResponseItemModel.ddiagnosetime = "";

                                payResultResponseItemModel.deptname = "";
                                payResultResponseItemModel.diagnoseid = "";
                                payResultResponseItemModel.doctorname = "";
                                payResultResponseItemModel.ndiagnosenum = "";
                                payResultResponseItemModel.nmoney = "";
                                payResultResponseItemModel.orderno = payResultRequestModel.orderid;
                                payResultResponseItemModel.hospsate = "";
                                payResultResponseItemModel.workid = "";
                                payResultResponseItemModel.resourceid = "";
                                payResultResponseItemModel.inum = "";
                                return payResultResponseItemModel;
                            }
                            else if (order_state != 1)
                            {
                                payResultResponseItemModel.code = order_state.ToString() + "003";
                                payResultResponseItemModel.msg = "【查询订单异常】：" + order_msg;
                                payResultResponseItemModel.oid = "";
                                payResultResponseItemModel.cdiagnosetypename = "";
                                payResultResponseItemModel.cflowcode = "";
                                payResultResponseItemModel.chousename = "";
                                payResultResponseItemModel.chousesectionname = "";
                                payResultResponseItemModel.cidentitycard = "";
                                payResultResponseItemModel.clocation = "";
                                payResultResponseItemModel.cpatientcode = "";
                                payResultResponseItemModel.cpatientname = "";
                                payResultResponseItemModel.csex = "";
                                payResultResponseItemModel.ddiagnosetime = "";

                                payResultResponseItemModel.deptname = "";
                                payResultResponseItemModel.diagnoseid = "";
                                payResultResponseItemModel.doctorname = "";
                                payResultResponseItemModel.ndiagnosenum = "";
                                payResultResponseItemModel.nmoney = "";
                                payResultResponseItemModel.orderno = payResultRequestModel.orderid;
                                payResultResponseItemModel.hospsate = "";
                                payResultResponseItemModel.workid = "";
                                payResultResponseItemModel.resourceid = "";
                                payResultResponseItemModel.inum = "";
                                return payResultResponseItemModel;
                            }
                            else if (yuyue_state == 1 && order_state == 1)
                            {
                                var mJObj_payorder = JArray.Parse(orderJson);
                                foreach (var drPayorder in mJObj_payorder)
                                {
                                    payResultResponseItemModel.code = order_state.ToString();
                                    payResultResponseItemModel.msg = order_msg;
                                    payResultResponseItemModel.oid =
                                        drPayorder["AppointmentOrder"]["OrderId"].ToString();

                                    string workid = ds.Tables[0].Rows[0]["wid"].ToString();
                                    if (string.Equals(workid, drPayorder["WorkSchedule"]["Code"].ToString()))
                                        payResultResponseItemModel.workid = drPayorder["WorkSchedule"]["Code"].ToString();
                                    else
                                        payResultResponseItemModel.workid = workid;

                                    payResultResponseItemModel.resourceid = drPayorder["WorkDetail"]["Code"].ToString();
                                    payResultResponseItemModel.inum = drPayorder["WorkDetail"]["AppointmentOrder"].ToString();
                                    payResultResponseItemModel.cdiagnosetypename =
                                        drPayorder["WorkSchedule"]["Doctor"]["Rank"].ToString();
                                    payResultResponseItemModel.cflowcode =
                                        CommonBLL.GetOrderId(drPayorder["AppointmentOrder"]["OrderId"].ToString(), 4);
                                    payResultResponseItemModel.chousename =
                                        drPayorder["WorkSchedule"]["VisitRoom"].ToString();
                                    payResultResponseItemModel.chousesectionname =
                                        drPayorder["WorkSchedule"]["VisitRoom"].ToString();
                                    payResultResponseItemModel.cidentitycard =
                                        drPayorder["Patient"]["IdentityCard"].ToString();
                                    payResultResponseItemModel.clocation =
                                        drPayorder["WorkSchedule"]["VisitRoom"].ToString();
                                    payResultResponseItemModel.cpatientcode =
                                        drPayorder["Patient"]["IdentityCard"].ToString();
                                    payResultResponseItemModel.cpatientname =
                                        drPayorder["Patient"]["PatientName"].ToString();
                                    payResultResponseItemModel.csex =
                                        drPayorder["Patient"]["Gender"].ToString();
                                    payResultResponseItemModel.ddiagnosetime =
                                        drPayorder["WorkSchedule"]["Date"].ToString();

                                    payResultResponseItemModel.deptname =
                                        drPayorder["WorkSchedule"]["Department"]["Name"].ToString();
                                    payResultResponseItemModel.diagnoseid =
                                        drPayorder["AppointmentOrder"]["OrderId"].ToString();
                                    payResultResponseItemModel.doctorname =
                                        drPayorder["WorkSchedule"]["Doctor"]["Name"].ToString();
                                    payResultResponseItemModel.ndiagnosenum =
                                        drPayorder["WorkDetail"]["AppointmentOrder"].ToString();
                                    payResultResponseItemModel.nmoney =
                                        drPayorder["AppointmentOrder"]["Amount"].ToString();
                                    payResultResponseItemModel.orderno = payResultRequestModel.orderid;
                                    payResultResponseItemModel.hospsate = drPayorder["AppointmentOrder"]["Status"].ToString();
                                }
                            }
                        }
                    }
                    else
                    {
                        payResultResponseItemModel.code = "-1000";
                        payResultResponseItemModel.msg = string.Format("【预约挂号异常】：订单号为空。");
                        payResultResponseItemModel.oid = "";
                        payResultResponseItemModel.cdiagnosetypename = "";
                        payResultResponseItemModel.cflowcode = "";
                        payResultResponseItemModel.chousename = "";
                        payResultResponseItemModel.chousesectionname = "";
                        payResultResponseItemModel.cidentitycard = "";
                        payResultResponseItemModel.clocation = "";
                        payResultResponseItemModel.cpatientcode = "";
                        payResultResponseItemModel.cpatientname = "";
                        payResultResponseItemModel.csex = "";
                        payResultResponseItemModel.ddiagnosetime = "";

                        payResultResponseItemModel.deptname = "";
                        payResultResponseItemModel.diagnoseid = "";
                        payResultResponseItemModel.doctorname = "";
                        payResultResponseItemModel.ndiagnosenum = "";
                        payResultResponseItemModel.nmoney = "";
                        payResultResponseItemModel.orderno = payResultRequestModel.orderid;
                        payResultResponseItemModel.hospsate = "";
                        payResultResponseItemModel.workid = "";
                        payResultResponseItemModel.resourceid = "";
                        payResultResponseItemModel.inum = "";
                        return payResultResponseItemModel;
                    }
                }
                catch (Exception err)
                {
                    payResultResponseItemModel.code = "-1000";
                    payResultResponseItemModel.msg = string.Format("【预约挂号异常，异常信息】：{0}", err.ToString());
                    payResultResponseItemModel.oid = "";
                    payResultResponseItemModel.cdiagnosetypename = "";
                    payResultResponseItemModel.cflowcode = "";
                    payResultResponseItemModel.chousename = "";
                    payResultResponseItemModel.chousesectionname = "";
                    payResultResponseItemModel.cidentitycard = "";
                    payResultResponseItemModel.clocation = "";
                    payResultResponseItemModel.cpatientcode = "";
                    payResultResponseItemModel.cpatientname = "";
                    payResultResponseItemModel.csex = "";
                    payResultResponseItemModel.ddiagnosetime = "";

                    payResultResponseItemModel.deptname = "";
                    payResultResponseItemModel.diagnoseid = "";
                    payResultResponseItemModel.doctorname = "";
                    payResultResponseItemModel.ndiagnosenum = "";
                    payResultResponseItemModel.nmoney = "";
                    payResultResponseItemModel.orderno = payResultRequestModel.orderid;
                    payResultResponseItemModel.hospsate = "";
                    payResultResponseItemModel.workid = "";
                    payResultResponseItemModel.resourceid = "";
                    payResultResponseItemModel.inum = "";
                    return payResultResponseItemModel;
                }

                //返回
                return payResultResponseItemModel;
            }
            catch (Exception err)
            {
                throw;
            }
        }

        private string GetOrderJson(string orderno, DataSet ds, out int yuyue_state, out string yuyue_msg
            , out int order_state, out string order_msg)
        {
            yuyue_state = order_state = 1;
            yuyue_msg = order_msg = "";
            string payorder_result = "";//查询HIS订单状态返回的报文
            string getorder_result = "";//查询HIS预约挂号返回的报文

            string orderid_his = "";
            #region 存储并判断是否已经请求HIS预约挂号接口
            PreeRegisterModel.hars_notifyhistask model = new PreeRegisterModel.hars_notifyhistask();
            model.createdate = model.lastdate = DateTime.Now;
            model.orderno = model.request = orderno;
            model.state = 0;
            hars_notifyhistask bll_notify = new hars_notifyhistask();
            DataSet ds_notify = bll_notify.GetList(string.Format("orderno='{0}'", orderno));

            //中间表没有数据，还未请求HIS预约挂号接口
            if (ds_notify.Tables[0].Rows.Count == 0)
            {
                if (!bll_notify.Add(model))
                {
                    yuyue_state = -7;
                    yuyue_msg = string.Format("hars_notifyhistask 插入失败，平台订单号：{0}", orderno);
                }

                #region 2019-02-26 提交预约之前，再去查一遍要预约的号源是否被预约，如果已经被预约，则查找最近没有被预约的号源进行预约
                int count = 99;
                int appstate = 0;
                string resourceidNew = "";
                string inumNew = "";
                string timeNew = "";

                string iid = ds.Tables[0].Rows[0]["iid"].ToString();
                DateTime dt = Convert.ToDateTime(CommonBLL.RemoveStr(ds.Tables[0].Rows[0]["tdate"].ToString()));//请求的就诊时间
                int days = CommonBLL.GetDays(DateTime.Now, dt) + 1;
                JObject obj_getiid = ChangZhiHePingBLL.GetOutPatientWorkSchedulesNew
                       (dt, ds.Tables[0].Rows[0]["doctorid"].ToString(), days, ds.Tables[0].Rows[0]["wid"].ToString(),
                            ds.Tables[0].Rows[0]["iid"].ToString(), out count, out appstate,
                       out resourceidNew, out inumNew, out timeNew);
                string code_getiid = obj_getiid["code"].ToString();
                if (string.Equals(code_getiid, "1"))
                {
                    var mJObj_getiid = JArray.Parse(obj_getiid["result"].ToString());
                    if (string.Equals(mJObj_getiid.ToString(), "[]"))
                    {
                        yuyue_state = -5;
                        yuyue_msg = string.Format("排班已过期，平台订单号：{0}", orderno);
                    }
                    if (!string.Equals(ds.Tables[0].Rows[0]["iid"].ToString(), resourceidNew))
                    {
                        //记录日志
                        CommonBLL.WriteFile_New(CommonBLL.bizCode_payResult,
                           string.Format("预约的号源被占用，重新选号，订单号{0},号源ID：{1},新号源ID：{2}：\r\n", orderno, iid, resourceidNew));
                        iid = resourceidNew;
                    }

                    #region 构造请求参数
                    string appointmentCode = iid;// ds.Tables[0].Rows[0]["iid"].ToString();
                    string patientId = ds.Tables[0].Rows[0]["card"].ToString();
                    string patientName = ds.Tables[0].Rows[0]["name"].ToString();
                    string identityCard = ds.Tables[0].Rows[0]["card"].ToString();
                    string birthday = ds.Tables[0].Rows[0]["birth"].ToString();
                    string gender = ds.Tables[0].Rows[0]["gender"].ToString() == "1" ? "男" : "女";
                    DateTime brith = Convert.ToDateTime(ds.Tables[0].Rows[0]["birth"].ToString());
                    string age = ds.Tables[0].Rows[0]["birth"].ToString() == "" ? "1" :
                        CommonBLL.GetAgeByBirthdate(brith).ToString();
                    string telephone = ds.Tables[0].Rows[0]["tel"].ToString();
                    string address = ds.Tables[0].Rows[0]["addr"].ToString();
                    string patientCode = "";// ds.Tables[0].Rows[0]["name"].ToString();
                    string patientCardCode = "";// ds.Tables[0].Rows[0]["name"].ToString();
                    string ageUnit = "岁";//ds.Tables[0].Rows[0]["name"].ToString();
                    string appointmentSource = CommonBLL.GetConfig("source") == "1" ? "趣医网" : "健康山西";
                    #endregion

                    #region 请求HIS预约挂号接口 并保存返回报文
                    JObject obj_getorder = ChangZhiHePingBLL.MakeOutPatientAppointment(appointmentCode
                        , patientId, patientName, identityCard, birthday, gender, age,
                      telephone, address, patientCode, patientCardCode, ageUnit, appointmentSource);

                    if (obj_getorder == null || obj_getorder.ToString().Length <= 0)
                    {
                        yuyue_state = -1000;
                        yuyue_msg = string.Format("请求预约接口异常，obj_getorder=" + obj_getorder);
                        if (!bll_notify.Update("-1000", orderno, "与HIS接口交互异常。"))
                        {
                            yuyue_state = -8;
                            yuyue_msg = string.Format("hars_notifyhistask 更新失败，平台订单号：{0}", orderno);
                        }

                        return payorder_result;
                    }
                    CommonBLL.WriteFile_New(CommonBLL.bizCode_payResult, "查询HIS预约挂号接口：\r\n" + CommonBLL.ConvertJsonString(obj_getorder.ToString()));
                    string code_getorder = obj_getorder["code"].ToString();
                    int.TryParse(code_getorder, out yuyue_state);
                    yuyue_msg = obj_getorder["msg"].ToString();
                    //保存HIS返回报文 判断如果code值是1，则读取result节点；如果不唯一则读取msg节点。
                    if (string.Equals(code_getorder, "1"))
                    {
                        getorder_result = string.IsNullOrEmpty(obj_getorder["result"].ToString()) ? "" : obj_getorder["result"].ToString();
                        var mJObj_getorder = JArray.Parse(getorder_result);
                        foreach (var drGetorder in mJObj_getorder)
                        {
                            orderid_his = drGetorder["AppointmentOrder"]["OrderId"].ToString();
                        }
                    }
                    else
                        getorder_result = string.IsNullOrEmpty(obj_getorder["msg"].ToString()) ? "" : obj_getorder["msg"].ToString();


                    if (!bll_notify.Update(code_getorder, orderno, getorder_result))
                    {
                        yuyue_state = -8;
                        yuyue_msg = string.Format("hars_notifyhistask 更新失败，平台订单号：{0}", orderno);
                    }


                    #endregion
                }
                else
                {
                    yuyue_state = -5;
                    yuyue_msg = string.Format("排班异常，平台订单号：{0}", orderno);
                }

                #endregion
            }

            //中间表有数据，并且code值为1，拿到中间表的预约挂号数据执行后续逻辑
            else if (ds_notify.Tables[0].Rows[0]["state"].ToString() == "1")
            {
                var mJObj_getorder = JArray.Parse(ds_notify.Tables[0].Rows[0]["response"].ToString());
                foreach (var drGetorder in mJObj_getorder)
                {
                    orderid_his = drGetorder["AppointmentOrder"]["OrderId"].ToString();
                }
            }
            //中间表有数据，但code值不为1
            else if (ds_notify.Tables[0].Rows[0]["state"].ToString() != "1")
            {
                int.TryParse(ds_notify.Tables[0].Rows[0]["state"].ToString(), out yuyue_state);
                yuyue_msg = string.IsNullOrEmpty(ds_notify.Tables[0].Rows[0]["response"].ToString()) ? ""
                    : ds_notify.Tables[0].Rows[0]["response"].ToString();
            }
            #region  如果不成功，则重新请求医院预约挂号接口 暂时关闭 原因：平台退费任务和支付结果通知任务可能会导致错单
            //如果不成功，则重新请求医院预约挂号接口
            //else if (ds_notify.Tables[0].Rows[0]["state"].ToString() != "1")
            //{
            //    #region 构造请求参数
            //    string appointmentCode = ds.Tables[0].Rows[0]["iid"].ToString();
            //    string patientId = ds.Tables[0].Rows[0]["card"].ToString();
            //    string patientName = ds.Tables[0].Rows[0]["name"].ToString();
            //    string identityCard = ds.Tables[0].Rows[0]["card"].ToString();
            //    string birthday = ds.Tables[0].Rows[0]["birth"].ToString();
            //    string gender = ds.Tables[0].Rows[0]["gender"].ToString() == "1" ? "男" : "女";
            //    DateTime brith = Convert.ToDateTime(ds.Tables[0].Rows[0]["birth"].ToString());
            //    string age = ds.Tables[0].Rows[0]["birth"].ToString() == "" ? "1" :
            //        CommonBLL.GetAgeByBirthdate(brith).ToString();
            //    string telephone = ds.Tables[0].Rows[0]["tel"].ToString();
            //    string address = ds.Tables[0].Rows[0]["addr"].ToString();
            //    string patientCode = "";// ds.Tables[0].Rows[0]["name"].ToString();
            //    string patientCardCode = "";// ds.Tables[0].Rows[0]["name"].ToString();
            //    string ageUnit = "岁";//ds.Tables[0].Rows[0]["name"].ToString();
            //    string appointmentSource = CommonBLL.GetConfig("source") == "1" ? "趣医网" : "健康山西";
            //    #endregion

            //    #region 请求HIS预约挂号接口 并保存返回报文
            //    JObject obj_getorder = ChangZhiHePingBLL.MakeOutPatientAppointment(appointmentCode
            //        , patientId, patientName, identityCard, birthday, gender, age,
            //      telephone, address, patientCode, patientCardCode, ageUnit, appointmentSource);
            //    //  CommonBLL.WriteFile_New(CommonBLL.bizCode_payResult, "查询HIS预约挂号接口：\r\n" + CommonBLL.ConvertJsonString(obj_getorder.ToString()));
            //    string code_getorder = obj_getorder["code"].ToString();

            //    int.TryParse(code_getorder, out yuyue_state);
            //    yuyue_msg = obj_getorder["msg"].ToString();

            //    //保存HIS返回报文 判断如果code值是1，则读取result节点；如果不唯一则读取msg节点。

            //    if (string.Equals(code_getorder, "1"))
            //    {
            //        getorder_result = string.IsNullOrEmpty(obj_getorder["result"].ToString()) ? "" : obj_getorder["result"].ToString();
            //        var mJObj_getorder = JArray.Parse(getorder_result);
            //        foreach (var drGetorder in mJObj_getorder)
            //        {
            //            orderid_his = drGetorder["AppointmentOrder"]["OrderId"].ToString();
            //        }
            //    }
            //    else
            //        getorder_result = string.IsNullOrEmpty(obj_getorder["msg"].ToString()) ? "" : obj_getorder["msg"].ToString();



            //    if (!bll_notify.Update(code_getorder, orderno, getorder_result))
            //    {
            //        yuyue_state = -8;
            //        yuyue_msg = string.Format("hars_notifyhistask 更新失败，平台订单号：{0}", orderno);
            //    }
            //    #endregion
            //}
            #endregion

            if (yuyue_state == 1 && !string.IsNullOrEmpty(orderid_his))
            {
                //根据HIS预约挂号返回的订单号 查询订单信息
                JObject obj_payorder = ChangZhiHePingBLL.GetAppointmentByOrderId(orderid_his);
                //CommonBLL.WriteFile_New(CommonBLL.bizCode_payResult, "查询HIS订单状态接口：\r\n" + CommonBLL.ConvertJsonString(obj_payorder.ToString()));
                string code_payorder = obj_payorder["code"].ToString();
                if (string.Equals(code_payorder, "1"))
                {
                    var mJObj_payorder = JArray.Parse(obj_payorder["result"].ToString());
                    foreach (var drPayorder in mJObj_payorder)
                    {
                        //if (string.Equals(drPayorder["AppointmentOrder"]["Status"].ToString(), "Available")//0
                        //    || string.Equals(drPayorder["AppointmentOrder"]["Status"].ToString(), "Charged")//2
                        //    || string.Equals(drPayorder["AppointmentOrder"]["Status"].ToString(), "Triaged"))//3
                        //{
                        order_state = 1;
                        order_msg = "支付成功";
                        payorder_result = mJObj_payorder.ToString();
                        //}
                    }
                }
                else
                {
                    int.TryParse(code_payorder, out order_state);
                    payorder_result = obj_payorder["msg"].ToString();
                }
            }
            #endregion
            return payorder_result;
        }
        #endregion

        #region 长治和平接口 住院患者查询

        /// <summary>
        /// 长治和平 查询住院患者信息【新】
        /// </summary>
        /// <param name="notPayRequestModel"></param>
        /// <returns></returns>
        public static ParentInfoResponseModel GetParentInfo(ParentInfoRequestModel parentInfoRequestModel)
        {
            //住院患者信息
            ParentInfoResponseModel parentInfoResponseModel = new ParentInfoResponseModel();
            try
            {
                string patientCode = parentInfoRequestModel.inpcode;
                //获取住院次数
                JObject obj_parent_times = ChangZhiHePingBLL.GetInhospitalPatientHistoryFeeInfo(patientCode);
                string code_parent_tims = obj_parent_times["code"].ToString();
                string msg_parent_tims = obj_parent_times["msg"].ToString();
                if (string.Equals(code_parent_tims, "1"))
                {
                    if (string.Equals(obj_parent_times["result"].ToString(), "[]"))
                    {
                        parentInfoResponseModel.code = "1";
                        parentInfoResponseModel.msg = string.Format(@"患者已出院，无住院次数，住院号：{0}", patientCode);
                        parentInfoResponseModel.state = "2";
                        return parentInfoResponseModel;
                    }
                    var mJObj_parent_times = JArray.Parse(obj_parent_times["result"].ToString())[0];//获取第0行数据
                    string times = mJObj_parent_times["HospitalizedTimes"].ToString();//住院次数
                    string leaveDate = mJObj_parent_times["FeeDateTime"].ToString(); //出院时间 FeeDateTime
                    if (!string.IsNullOrEmpty(leaveDate))
                    {
                        //查询失败，返回出院状态 edit by zhuyr 2019-04-29
                        parentInfoResponseModel.code = "1";
                        parentInfoResponseModel.state = "2";
                        DateTime dt_outdate = Convert.ToDateTime(leaveDate);//出院时间
                        parentInfoResponseModel.leaveDate = dt_outdate.ToString("yyyy-MM-dd HH:mm:ss").Trim();
                        parentInfoResponseModel.msg = "患者已出院。";
                        parentInfoResponseModel.InPcode = parentInfoRequestModel.inpcode;//住院号
                        parentInfoResponseModel.times = times;
                        parentInfoResponseModel.age = mJObj_parent_times["Age"] == null ? "" : mJObj_parent_times["Age"].ToString().Replace("岁", "").Trim();//年龄
                        parentInfoResponseModel.bednum = mJObj_parent_times["BedCode"] == null ? "" : mJObj_parent_times["BedCode"].ToString().Trim();//床号
                        DateTime dt_indate = Convert.ToDateTime(mJObj_parent_times["InHospitalDate"].ToString());//住院时间
                        parentInfoResponseModel.admissionDate = dt_indate.ToString("yyyy-MM-dd HH:mm:ss").Trim();//住院时间
                        parentInfoResponseModel.deptid = "";//住院科室ID
                        parentInfoResponseModel.deptname = "";//住院科室名称
                        parentInfoResponseModel.docname = "";//医生姓名
                        parentInfoResponseModel.doctid = "";//主治医生ID
                        parentInfoResponseModel.hospid = CommonBLL.GetConfig("hospitalid");//医院ID
                        parentInfoResponseModel.hospname = CommonBLL.GetConfig("hospitalname");//医院名称
                        parentInfoResponseModel.identityCard = "";//患者身份证号码    确认
                        parentInfoResponseModel.mtype = "";//医保类型
                        parentInfoResponseModel.PatientName = "";//患者姓名
                        parentInfoResponseModel.tel = "";//患者手机号
                        string pid = "";
                        parentInfoResponseModel.pid = pid;//患者唯一索引 
                        parentInfoResponseModel.gender = "";//性别
                        return parentInfoResponseModel;
                    }
                    DateTime dt_times = Convert.ToDateTime(mJObj_parent_times["InHospitalDate"].ToString());//住院日期 判断住院状态
                    if (DateTime.Compare(dt_times, DateTime.Now) < 0)
                    {
                        JObject obj_parent_msg = ChangZhiHePingBLL.GetInhospitalPatientInfo(patientCode, times);
                        if (string.Equals(obj_parent_msg["result"].ToString(), "[]"))
                        {
                            parentInfoResponseModel.code = "1";
                            parentInfoResponseModel.msg = string.Format(@"患者已出院，没有查询到患者信息，住院号：{0}", patientCode);
                            parentInfoResponseModel.state = "2";
                            return parentInfoResponseModel;
                        }
                        string code_parent_msg = obj_parent_msg["code"].ToString();
                        string msg_parent_msg = obj_parent_msg["msg"].ToString();
                        if (string.Equals(code_parent_msg, "1"))
                        {
                            var mJObj_parent_msg = JArray.Parse(obj_parent_msg["result"].ToString());
                            foreach (var dr_parent_msg in mJObj_parent_msg)
                            {
                                parentInfoResponseModel.code = code_parent_msg;
                                parentInfoResponseModel.msg = "查询住院患者信息成功。";
                                parentInfoResponseModel.state = "1";//住院状态 根据住院时间判断
                                parentInfoResponseModel.InPcode = dr_parent_msg["PatientCode"].ToString().Trim();//住院号
                                parentInfoResponseModel.times = dr_parent_msg["HospitalizedTimes"].ToString().Trim();//住院次数
                                parentInfoResponseModel.age = dr_parent_msg["Age"] == null ? "" : dr_parent_msg["Age"].ToString().Replace("岁", "").Trim();//年龄
                                parentInfoResponseModel.bednum = dr_parent_msg["BedCode"] == null ? "" : dr_parent_msg["BedCode"].ToString().Trim();//床号
                                DateTime dt = Convert.ToDateTime(dr_parent_msg["InHospitalDate"].ToString());//住院日期
                                parentInfoResponseModel.admissionDate = dt.ToString("yyyy-MM-dd HH:mm:ss").Trim();//住院日期
                                parentInfoResponseModel.deptid = dr_parent_msg["InDept"] == null ? "" : dr_parent_msg["InDept"].ToString().Trim();//住院科室ID
                                parentInfoResponseModel.deptname = dr_parent_msg["InDeptName"] == null ? "" : dr_parent_msg["InDeptName"].ToString().Trim();//住院科室名称
                                parentInfoResponseModel.docname = dr_parent_msg["OpenDoctorName"] == null ? "" : dr_parent_msg["OpenDoctorName"].ToString().Trim();//医生姓名      确认
                                parentInfoResponseModel.doctid = dr_parent_msg["DoctorCode"] == null ? "" : dr_parent_msg["DoctorCode"].ToString().Trim(); //主治医生ID
                                parentInfoResponseModel.hospid = CommonBLL.GetConfig("hospitalid");//医院ID
                                parentInfoResponseModel.hospname = CommonBLL.GetConfig("hospitalname");//医院名称
                                parentInfoResponseModel.identityCard = dr_parent_msg["IdentityCard"] == null ? "" : dr_parent_msg["IdentityCard"].ToString().Trim();//患者身份证号码    确认
                                parentInfoResponseModel.mtype = dr_parent_msg["PatientType"] == null ? "" : dr_parent_msg["PatientType"].ToString().Trim();//医保类型
                                parentInfoResponseModel.PatientName = dr_parent_msg["PatientName"] == null ? "" : dr_parent_msg["PatientName"].ToString().Trim();//患者姓名

                                //ischangephone 0否 1是 将住院患者的手机号更换为测试手机，避免测试阶段下发短信到患者手机
                                if (string.Equals(CommonBLL.GetConfig("ischangephone"), "1"))
                                    parentInfoResponseModel.tel = CommonBLL.GetConfig("testphone");
                                else
                                    parentInfoResponseModel.tel = dr_parent_msg["ContacterPhone"] == null ? "" : dr_parent_msg["ContacterPhone"].ToString().Trim(); //患者手机号
                                parentInfoResponseModel.pid = CommonBLL.GetPid(parentInfoResponseModel.InPcode, parentInfoResponseModel.times);//患者唯一索引 
                                string gender = dr_parent_msg["Sex"] == null ? "" : dr_parent_msg["Sex"].ToString();

                                parentInfoResponseModel.gender = CommonBLL.GetGender(gender); //性别
                                parentInfoResponseModel.leaveDate = "";//出院日期
                                return parentInfoResponseModel;
                            }
                        }
                        else
                        {
                            //查询失败，返回出院状态 edit by zhuyr 2019-04-29
                            parentInfoResponseModel.code = "1";// code_parent_msg;
                            parentInfoResponseModel.state = "2";
                            parentInfoResponseModel.leaveDate = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
                            parentInfoResponseModel.msg = "获取住院患者信息异常：" + code_parent_msg + "|" + msg_parent_msg;
                            parentInfoResponseModel.InPcode = parentInfoRequestModel.inpcode;//住院号
                            parentInfoResponseModel.times = times;
                            parentInfoResponseModel.age = "";//年龄
                            parentInfoResponseModel.bednum = "";//床号

                            parentInfoResponseModel.admissionDate = "";//住院日期
                            parentInfoResponseModel.deptid = "";//住院科室ID
                            parentInfoResponseModel.deptname = "";//住院科室名称
                            parentInfoResponseModel.docname = "";//医生姓名      确认
                            parentInfoResponseModel.doctid = "";//主治医生ID
                            parentInfoResponseModel.hospid = CommonBLL.GetConfig("hospitalid");//医院ID
                            parentInfoResponseModel.hospname = CommonBLL.GetConfig("hospitalname");//医院名称
                            parentInfoResponseModel.identityCard = "";//患者身份证号码    确认
                            parentInfoResponseModel.mtype = "";//医保类型
                            parentInfoResponseModel.PatientName = "";//患者姓名
                            parentInfoResponseModel.tel = "";//患者手机号
                            string pid = "";
                            parentInfoResponseModel.pid = pid;//患者唯一索引 
                            parentInfoResponseModel.gender = "";//性别
                            return parentInfoResponseModel;
                        }
                    }
                    else
                    {
                        parentInfoResponseModel.code = "0";
                        parentInfoResponseModel.msg = string.Format(@"患者住院日期大于当前时间，
                            请核实。住院号：{0}，住院日期：{1}", patientCode, dt_times);
                        return parentInfoResponseModel;
                    }

                }
                else
                {
                    //查询失败，返回出院状态 edit by zhuyr 2019-04-29
                    parentInfoResponseModel.code = "1";// code_parent_tims;
                    parentInfoResponseModel.state = "2";
                    parentInfoResponseModel.leaveDate = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
                    parentInfoResponseModel.msg = "获取住院次数异常：" + code_parent_tims + "|" + msg_parent_tims;
                    parentInfoResponseModel.InPcode = parentInfoRequestModel.inpcode;//住院号
                    parentInfoResponseModel.age = "";//年龄
                    parentInfoResponseModel.bednum = "";//床号

                    parentInfoResponseModel.admissionDate = "";//住院日期
                    parentInfoResponseModel.deptid = "";//住院科室ID
                    parentInfoResponseModel.deptname = "";//住院科室名称
                    parentInfoResponseModel.docname = "";//医生姓名      确认
                    parentInfoResponseModel.doctid = "";//主治医生ID
                    parentInfoResponseModel.hospid = CommonBLL.GetConfig("hospitalid");//医院ID
                    parentInfoResponseModel.hospname = CommonBLL.GetConfig("hospitalname");//医院名称
                    parentInfoResponseModel.identityCard = "";//患者身份证号码    确认
                    parentInfoResponseModel.mtype = "";//医保类型
                    parentInfoResponseModel.PatientName = "";//患者姓名
                    parentInfoResponseModel.tel = "";//患者手机号
                    string pid = "";
                    parentInfoResponseModel.pid = pid;//患者唯一索引 
                    parentInfoResponseModel.gender = "";//性别
                    return parentInfoResponseModel;
                }
                //返回
                CommonBLL.WriteFile_New(CommonBLL.bizCode_searchNopay, parentInfoResponseModel.msg);
            }
            catch (Exception err)
            {
                parentInfoResponseModel.code = "-1000";
                parentInfoResponseModel.msg = "住院患者信息查询异常1:" + err.Message;
                return parentInfoResponseModel;
            }
            return parentInfoResponseModel;
        }
        #endregion

        #region 其他接口

        /// <summary>
        /// 查询就诊状态
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public static DiagnoseStateResponseModel DiagnoseState(DiagnoseStateRequestModel diagnoseStateRequestModel)
        {
            try
            {
                DataSet ds = new DataSet();
                //查询就诊状态
                DiagnoseStateResponseModel diagnoseStateResponseModel = new PreeRegisterModel.DiagnoseStateResponseModel();

                //判断入口参数是否有diagnoseid
                if (diagnoseStateRequestModel.diagnoseid.ToString().Trim() == "0")
                {
                    //判断是否同煤
                    if (VariableBLL.IFTmkyy)
                    {
                        bool registerflag = SearchDAL.getregisterflag(diagnoseStateRequestModel);
                        if (registerflag)
                        {
                            ds = SearchDAL.DiagnoseState_tmkyy(diagnoseStateRequestModel);
                        }
                        else
                        {
                            diagnoseStateResponseModel.diagnoseflag = 0;
                            return diagnoseStateResponseModel;
                        }
                    }
                }
                else
                {
                    ds = SearchDAL.DiagnoseState(diagnoseStateRequestModel);
                }
                if (ds == null)
                {
                    return null;
                }

                diagnoseStateResponseModel.diagnoseflag = Common.ToInt(ds.Tables[0].Rows[0][0].ToString());

                //返回
                return diagnoseStateResponseModel;
            }
            catch (Exception err)
            {

                throw;
            }
        }

        /// <summary>
        /// 查询排队叫号
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public static ClinicQueueResponseModel ClinicQueue(ClinicQueueRequestModel clinicQueueRequestModel)
        {
            try
            {
                //查询排队叫号
                ClinicQueueResponseModel clinicQueueResponseModel = new PreeRegisterModel.ClinicQueueResponseModel();

                DataSet ds = SearchDAL.ClinicQueue(clinicQueueRequestModel);

                if (ds == null)
                {
                    return null;
                }

                clinicQueueResponseModel.CurrentCallNo = ds.Tables[0].Rows[0]["CurrentCallNo"].ToString();
                clinicQueueResponseModel.DeptCode = ds.Tables[0].Rows[0]["DeptCode"].ToString();
                clinicQueueResponseModel.DeptName = ds.Tables[0].Rows[0]["DeptName"].ToString();
                clinicQueueResponseModel.NotCallNum = ds.Tables[0].Rows[0]["NotCallNum"].ToString();
                clinicQueueResponseModel.staffname = ds.Tables[0].Rows[0]["staffname"].ToString();

                //获取排队叫号
                List<ClinicQueueResponseItemModel> ClinicQueueResponseItemModel_list = new List<ClinicQueueResponseItemModel>();

                foreach (DataRow drClinicQueue in ds.Tables[1].Rows)
                {
                    ClinicQueueResponseItemModel clinicQueueResponseItemModel = new ClinicQueueResponseItemModel();

                    clinicQueueResponseItemModel.cCardCode = drClinicQueue["cCardCode"].ToString();
                    clinicQueueResponseItemModel.cFamilyTel = drClinicQueue["cFamilyTel"].ToString();
                    clinicQueueResponseItemModel.cPatientName = drClinicQueue["cPatientName"].ToString();
                    clinicQueueResponseItemModel.dRegisterDate = drClinicQueue["dRegisterDate"].ToString();
                    clinicQueueResponseItemModel.iRegisterNo = drClinicQueue["iRegisterNo"].ToString();

                    ClinicQueueResponseItemModel_list.Add(clinicQueueResponseItemModel);
                }

                clinicQueueResponseModel.patients = ClinicQueueResponseItemModel_list;

                //返回
                return clinicQueueResponseModel;
            }
            catch (Exception err)
            {

                throw;
            }
        }

        /// <summary>
        /// 查询门诊已缴费
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public static ClinicFareResponseModel ClinicFare(ClinicFareRequestModel clinicFareRequestModel)
        {
            try
            {
                //查询门诊已缴费
                ClinicFareResponseModel clinicFareResponseModel = new PreeRegisterModel.ClinicFareResponseModel();

                DataSet ds = SearchDAL.ClinicFare(clinicFareRequestModel);

                //获取排队叫号
                List<ClinicFareResponseItemModel> ClinicFareResponseItemModel_list = new List<ClinicFareResponseItemModel>();

                foreach (DataRow drClinicFare in ds.Tables[0].Rows)
                {
                    ClinicFareResponseItemModel clinicFareResponseItemModel = new ClinicFareResponseItemModel();

                    clinicFareResponseItemModel.ccheckcode = drClinicFare["ccheckcode"].ToString();
                    clinicFareResponseItemModel.cItemCode = drClinicFare["cItemCode"].ToString();
                    clinicFareResponseItemModel.cItemName = drClinicFare["cItemName"].ToString();
                    clinicFareResponseItemModel.cRateType = drClinicFare["cRateType"].ToString();
                    clinicFareResponseItemModel.cStandard = drClinicFare["cStandard"].ToString();
                    clinicFareResponseItemModel.faredate = drClinicFare["DT"].ToString();
                    clinicFareResponseItemModel.nMoney = drClinicFare["nMoney"].ToString();
                    clinicFareResponseItemModel.nNum = drClinicFare["nNum"].ToString();
                    clinicFareResponseItemModel.nPrice = drClinicFare["nPrice"].ToString();
                    clinicFareResponseItemModel.totalMoney = drClinicFare["totalMoney"].ToString();
                    clinicFareResponseItemModel.idetailid = drClinicFare["iFlowID"].ToString();
                    clinicFareResponseItemModel.cInterPayFromType = drClinicFare["cInterPayFromType"].ToString();

                    ClinicFareResponseItemModel_list.Add(clinicFareResponseItemModel);
                }

                clinicFareResponseModel.items = ClinicFareResponseItemModel_list;

                //返回
                return clinicFareResponseModel;
            }
            catch (Exception err)
            {

                throw;
            }
        }

        /// <summary>
        /// 住院费用查询
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public static HospitalFareResponseModel HospitalFare(HospitalFareRequestModel HospitalFareRequestModel)
        {
            try
            {
                //住院费用查询
                HospitalFareResponseModel hospitalFareResponseModel = new PreeRegisterModel.HospitalFareResponseModel();

                DataSet ds = SearchDAL.HospitalFare(HospitalFareRequestModel);

                if (ds == null)
                {
                    return null;
                }

                //赋值
                hospitalFareResponseModel.AdmissionDate = ds.Tables[0].Rows[0]["AdmissionDate"].ToString();
                hospitalFareResponseModel.BedCode = ds.Tables[0].Rows[0]["BedCode"].ToString();
                hospitalFareResponseModel.InPCode = ds.Tables[0].Rows[0]["InPCode"].ToString();
                hospitalFareResponseModel.leftmoney = ds.Tables[0].Rows[0]["ye"].ToString();
                hospitalFareResponseModel.No_TreatList = ds.Tables[0].Rows[0]["No_TreatList"].ToString();
                hospitalFareResponseModel.PatName = ds.Tables[0].Rows[0]["PatName"].ToString();
                hospitalFareResponseModel.PayMoney = ds.Tables[0].Rows[0]["PayMoney"].ToString();
                hospitalFareResponseModel.RoomName = ds.Tables[0].Rows[0]["RoomName"].ToString();
                hospitalFareResponseModel.totalfare = ds.Tables[0].Rows[0]["totalfare"].ToString();
                hospitalFareResponseModel.MarkOutdate = ds.Tables[0].Rows[0]["MarkOutdate"].ToString();
                hospitalFareResponseModel.DeptName = ds.Tables[0].Rows[0]["DeptName"].ToString();

                List<HospitalFareResponseItemModel> HospitalFareResponseItemModel_list = new List<HospitalFareResponseItemModel>();

                foreach (DataRow drHospitalFare in ds.Tables[1].Rows)
                {
                    HospitalFareResponseItemModel hospitalFareResponseItemModel = new HospitalFareResponseItemModel();

                    hospitalFareResponseItemModel.FareClassName = drHospitalFare["FareClassName"].ToString();
                    hospitalFareResponseItemModel.FareItemName = drHospitalFare["FareItemName"].ToString();
                    hospitalFareResponseItemModel.FareItemSpec = drHospitalFare["FareItemSpec"].ToString();
                    hospitalFareResponseItemModel.FareItemUnit = drHospitalFare["FareItemUnit"].ToString();
                    hospitalFareResponseItemModel.InFactMoney = drHospitalFare["InFactMoney"].ToString();
                    hospitalFareResponseItemModel.InMoney = drHospitalFare["InMoney"].ToString();
                    hospitalFareResponseItemModel.Quantity = drHospitalFare["Quantity"].ToString();
                    hospitalFareResponseItemModel.InTime = drHospitalFare["InTime"].ToString();

                    HospitalFareResponseItemModel_list.Add(hospitalFareResponseItemModel);
                }

                hospitalFareResponseModel.items = HospitalFareResponseItemModel_list;

                //返回
                return hospitalFareResponseModel;
            }
            catch (Exception err)
            {

                throw;
            }
        }

        /// <summary>
        /// 人工窗口退费查询
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public static WindowFadeFareResponseModel WindowFadeFare(WindowFadeFareRequestModel windowFadeFareRequestModel)
        {
            try
            {
                //人工窗口退费查询
                WindowFadeFareResponseModel windowFadeFareResponseModel = new PreeRegisterModel.WindowFadeFareResponseModel();

                DataSet ds = SearchDAL.WindowFadeFare(windowFadeFareRequestModel);

                if (ds == null || ds.Tables[0].Rows.Count < 1)
                {
                    windowFadeFareResponseModel.code = "0";
                    windowFadeFareResponseModel.msg = "未查询到记录";
                    return windowFadeFareResponseModel;
                }

                //赋值
                windowFadeFareResponseModel.code = "1";
                windowFadeFareResponseModel.msg = "查询记录成功！";

                List<WindowFadeFareResponseResultModel> windowFadeFareResponseResultModel_list = new List<WindowFadeFareResponseResultModel>();

                foreach (DataRow drWindowFadeFare in ds.Tables[0].Rows)
                {
                    WindowFadeFareResponseResultModel windowFadeFareResponseResultModel = new WindowFadeFareResponseResultModel();
                    windowFadeFareResponseResultModel.cFlowCode = ds.Tables[0].Rows[0]["cFlowCode"].ToString();
                    windowFadeFareResponseResultModel.cPatientCode = ds.Tables[0].Rows[0]["cPatientCode"].ToString();
                    windowFadeFareResponseResultModel.cPatientName = ds.Tables[0].Rows[0]["cPatientName"].ToString();
                    windowFadeFareResponseResultModel.cRateType = ds.Tables[0].Rows[0]["cRateType"].ToString();
                    windowFadeFareResponseResultModel.nMoney = ds.Tables[0].Rows[0]["nMoney"].ToString();

                    windowFadeFareResponseResultModel_list.Add(windowFadeFareResponseResultModel);
                }

                windowFadeFareResponseModel.result = windowFadeFareResponseResultModel_list;

                //返回
                return windowFadeFareResponseModel;
            }
            catch (Exception err)
            {

                throw;
            }
        }

        /// <summary>
        /// 门诊费用发票号查询
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public static ClinicFareBillNumResponseModel ClinicFareBillNum(ClinicFareBillNumRequestModel clinicFareBillNumRequestModel)
        {
            try
            {
                //门诊费用发票号查询
                ClinicFareBillNumResponseModel clinicFareBillNumResponseModel = new PreeRegisterModel.ClinicFareBillNumResponseModel();

                DataSet ds = SearchDAL.ClinicFareBillNum(clinicFareBillNumRequestModel);

                if (ds == null || ds.Tables[0].Rows.Count < 1)
                {
                    clinicFareBillNumResponseModel.code = "0";
                    clinicFareBillNumResponseModel.msg = "未查询到记录";
                    return clinicFareBillNumResponseModel;
                }

                //判断是否打印发票号 liujia151124
                if (ds.Tables[0].Rows[0]["cBillCode"].ToString().Trim() == "" || ds.Tables[0].Rows[0]["cBillCode"].ToString().Trim() == "无")
                {
                    clinicFareBillNumResponseModel.code = "0";
                    clinicFareBillNumResponseModel.msg = "未查询到打印的发票号！";
                    clinicFareBillNumResponseModel.billcode = ds.Tables[0].Rows[0]["cBillCode"].ToString();
                }
                else
                {
                    clinicFareBillNumResponseModel.code = "1";
                    clinicFareBillNumResponseModel.msg = "查询到打印的发票号！";
                    clinicFareBillNumResponseModel.billcode = ds.Tables[0].Rows[0]["cBillCode"].ToString();
                }

                //返回
                return clinicFareBillNumResponseModel;
            }
            catch (Exception err)
            {

                throw;
            }
        }

        /// <summary>
        /// 置人工窗口退费流水已获取标志  liujia151208
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public static SetWFFFlagResponseModel SetWFFFlag(SetWFFFlagRequestModel setWFFFlagRequestModel)
        {
            try
            {
                //置人工窗口退费流水已获取标志
                SetWFFFlagResponseModel setWFFFlagResponseModel = new PreeRegisterModel.SetWFFFlagResponseModel();

                if (SearchDAL.SetWFFFlag(setWFFFlagRequestModel))
                {
                    setWFFFlagResponseModel.code = "1";
                    setWFFFlagResponseModel.msg = "回置人工窗口退费流水标志成功！";
                }
                else
                {
                    setWFFFlagResponseModel.code = "0";
                    setWFFFlagResponseModel.msg = "回置人工窗口退费流水标志失败！";
                }

                //返回
                return setWFFFlagResponseModel;
            }
            catch (Exception err)
            {

                throw;
            }
        }

        /// <summary>
        /// 查询挂号记录  liujia151226
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public static RegisterRecordResponseModel RegisterRecord(RegisterRecordRequestModel registerRecordRequestModel)
        {
            try
            {
                DataSet dsRegister = new DataSet();

                RegisterRecordResponseModel registerRecordResponseModel = new PreeRegisterModel.RegisterRecordResponseModel();

                //根据诊疗ID号与排班信息查询挂号记录
                if (registerRecordRequestModel.orderid.Trim() == "")
                {
                    string wid = WorkGetDAL.GetWorkPlanID(registerRecordRequestModel.doctorid.Trim(), registerRecordRequestModel.date.Trim(), registerRecordRequestModel.time.Trim());

                    dsRegister = SearchDAL.GetRegisterRecord_ByPatientCodeAndWid(registerRecordRequestModel, wid);
                }
                else  //根据预约订单号查询挂号记录
                {
                    dsRegister = SearchDAL.GetRegisterRecord_ByOrderid(registerRecordRequestModel);
                }

                if (dsRegister == null || dsRegister.Tables[0].Rows.Count < 1)
                {
                    registerRecordResponseModel.code = "0";
                    registerRecordResponseModel.msg = "查询挂号记录失败：未查询到挂号记录！";
                    return registerRecordResponseModel;
                }

                //查询就诊记录
                DataSet dsDiagnose = new DataSet();

                DiagnoseStateRequestModel diagnoseStateRequestModel = new DiagnoseStateRequestModel();
                diagnoseStateRequestModel.diagnoseid = Common.ToInt(dsRegister.Tables[0].Rows[0]["iDiagnoseCode"]);
                dsDiagnose = SearchDAL.DiagnoseState(diagnoseStateRequestModel);
                if (dsDiagnose == null)
                {
                    registerRecordResponseModel.code = "0";
                    registerRecordResponseModel.msg = "查询挂号记录失败：未查询到就诊记录！";
                    return registerRecordResponseModel;
                }

                //赋值挂号与就诊数据
                registerRecordResponseModel.code = "1";
                registerRecordResponseModel.msg = "查询挂号记录成功！";
                registerRecordResponseModel.deptname = dsRegister.Tables[0].Rows[0]["DeptName"].ToString();
                registerRecordResponseModel.doctorname = dsRegister.Tables[0].Rows[0]["StaffName"].ToString();
                registerRecordResponseModel.ddiagnosetime = Common.ToDateTime(dsRegister.Tables[0].Rows[0]["dstarttime"]).ToShortDateString();
                registerRecordResponseModel.time = dsRegister.Tables[0].Rows[0]["cTimeTypeName"].ToString();
                registerRecordResponseModel.ndiagnosenum = dsRegister.Tables[0].Rows[0]["nDiagnoseNum"].ToString();
                registerRecordResponseModel.cflowcode = dsRegister.Tables[0].Rows[0]["cFlowCode"].ToString();
                registerRecordResponseModel.diagnoseid = dsRegister.Tables[0].Rows[0]["iDiagnoseCode"].ToString();
                registerRecordResponseModel.diagnoseflag = dsDiagnose.Tables[0].Rows[0]["diagnoseflag"].ToString();
                registerRecordResponseModel.cpatientcode = dsRegister.Tables[0].Rows[0]["cPatientCode"].ToString();
                registerRecordResponseModel.cpatientname = dsRegister.Tables[0].Rows[0]["cPatientName"].ToString();

                //返回
                return registerRecordResponseModel;
            }
            catch (Exception err)
            {

                throw;
            }
        }

        #endregion
    }
}
